/**
 * 调仓记录
 * @author tongsitong
 */
import styled from "styled-components";
import { PageWrapper } from "@/components/PageWrapper";
import { Title } from "@/components/Title";
import { RenderDesc } from "../FixedAssets";
import {
  DateLine,
  DateList,
  DisplayTable,
  FlexStart,
  PreviewEmpty,
  TableWrapper,
  Td,
  Th,
  Tr,
} from "@/components/FOF/PreviewTable";
import { useEffect, useState } from "react";
import { getPositionHistory } from "./service";
import Pie from "@/components/EchartsComponents/Pie/pie";
import LittleTitle from "@/components/Title/littleTitle";
import { getBaseColors, getExpandColors } from "@/utils/echarts";
import EventEmpty from "@/components/FOF/EventEmpty";
import styles from "@/pages/PortfolioOverview/index.less";
import { Spin } from "antd";
import { query_profit_and_benchmark } from "../PortfolioOverview/portfolio";
import { getUrlParam } from "@/utils/utils";
import EventLine from "@/components/EchartsComponents/Line/EventLine";
import dayjs from 'dayjs';

// 定义在外部不会被重新渲染，但是useEffect里需要赋值，否则跳转时候不会更新
let positionDate = getUrlParam("positionDate");
let portfolioCode = getUrlParam("id");
let portfolioName = decodeURIComponent(getUrlParam("name"));

export function ChangePosition() {
  type ObjectT = {
    [key: string]: string;
  };

  const [activeDateIndex, setActiveDateIndex] = useState(0); // 选中的日期index
  const [historyList, setHistoryList] = useState([]); // 调仓历史列表
  const [loadingEvent, setLoadingEvent] = useState<boolean>(false);
  const [xAxis, setXAxis] = useState([]);
  const [legend, setLegend] = useState([]);
  const [yAxis, setYAxis] = useState([]);
  const [chartTitle, setChartTitle] = useState<ObjectT>({});

  const pieOptions = {
    legendProps: {
      right: "0%",
      top: "5%",
      left: "68%",
      height: 150,
      itemGap: 1,
    },
    pieStyle: {
      width: "80%",
      height: "80%",
      radius: ["60%", "85%"],
    },
    seriesType: {
      left: "-3%",
      top: "-3%",
    },
    formatLen: 7,
    color: [...getBaseColors(), ...getExpandColors()],
  };

  const testYData = [
    {
      label: "中证混合基金指数（选这个）",
      sort: "1",
      value: [
        { title: "中证混合基金指数（选这个）", key: "2022-06-01", value: 0 },
        { title: "中证混合基金指数（选这个）", key: "2022-06-02", value: 0.7 },
        { title: "中证混合基金指数（选这个）", key: "2022-06-06", value: 2.73 },
        { title: "中证混合基金指数（选这个）", key: "2022-06-07", value: 2.72 },
        { title: "中证混合基金指数（选这个）", key: "2022-06-08", value: 3.42 },
        { title: "中证混合基金指数（选这个）", key: "2022-06-09", value: 2.14 },
      ],
    },
    {
      label: "发射点风格上帝发誓",
      sort: "0",
      value: [
        {
          title: "发射点风格上帝发誓",
          key: "2022-06-01",
          value: 0,
          content: true,
        },
        {
          title: "发射点风格上帝发誓",
          key: "2022-06-02",
          value: 0,
          content: true,
        },
        { title: "发射点风格上帝发誓", key: "2022-06-06", value: 0 },
        { title: "发射点风格上帝发誓", key: "2022-06-07", value: 0 },
        { title: "发射点风格上帝发誓", key: "2022-06-08", value: 0 },
        { title: "发射点风格上帝发誓", key: "2022-06-09", value: 0 },
      ],
    },
  ];
  const testXData = [
    "2022-06-01",
    "2022-06-02",
    "2022-06-06",
    "2022-06-07",
    "2022-06-08",
    "2022-06-09",
  ];
  const testLegendData = ["中证混合基金指数（选这个）", "发射点风格上帝发誓"];

  const changeDate = (index: number) => {
    setActiveDateIndex(index);
    console.log(index);
  };

  useEffect(() => {
    getPositionHistory({
      // portfolioCode: "FOF_DEMO001",
      portfolioCode,
    }).then((res) => {
      setHistoryList(res?.data?.record);
    });

    // 业绩走势
    query_profit_and_benchmark({
      portfolioCode,
    }).then((res: any) => {
      setLoadingEvent(false);
      if (res?.code === "0") {
        setXAxis(res?.data?.xaxis);
        if (res?.data?.yaxis[0].label === portfolioName) {
          res?.data?.yaxis.reverse();
          setYAxis(res?.data?.yaxis);
          setLegend(res?.data?.yaxis.map((v) => v.label));
        } else {
          setYAxis(res?.data?.yaxis);
          setLegend(res?.data?.yaxis.map((v) => v.label));
        }

        setChartTitle({
          title: res.data.titles,
          endDate: dayjs(res.data.endDate).format("YYYY/MM/DD"),
          startDate: dayjs(res.data.startDate).format("YYYY/MM/DD"),
        });
      }
    });
  }, []);
  // 点击走势图上的红点
  const onClickPoint = (date: string) => {
    setActiveDateIndex(historyList.findIndex((v) => v.buyDate == date));
  };

  const getData = async () => {
    // 历史持仓
    let response = await getPositionHistory({ portfolioCode }); // portfolioCode: "FOF_DEMO001"
    setHistoryList(response?.data?.record);
    // 从概览页跳过来时指定时间
    if (positionDate) {
      response?.data?.record?.map((line, index) => {
        if (line.buyDate == positionDate) {
          setActiveDateIndex(index);
        }
      });
    }

    // 业绩走势
    let res = await query_profit_and_benchmark({ portfolioCode });
    setLoadingEvent(false);
    if (res?.code === "0") {
      setXAxis(res?.data?.xaxis);

      if (res?.data?.yaxis[0].label === portfolioName) {
        res?.data?.yaxis.reverse();
      }
      res?.data?.yaxis[1]?.value?.map((value) => {
        if (response?.data?.buyDate.indexOf(value.key) > -1) {
          value.content = true;
        }
      });

      setYAxis(res?.data?.yaxis);
      setLegend(res?.data?.yaxis.map((v) => v.label));
      setChartTitle({
        title: res.data.titles,
        endDate: dayjs(res.data.endDate).format("YYYY/MM/DD"),
        startDate: dayjs(res.data.startDate).format("YYYY/MM/DD"),
      });
    }
  };
  useEffect(() => {
    getData();
    positionDate = getUrlParam("positionDate");
    portfolioCode = getUrlParam("id");
    portfolioName = decodeURIComponent(getUrlParam("name"));
  }, []);

  return (
    <PageWrapper narrow scrollY>
      <Title style={{ marginLeft: 16 }}>调仓记录</Title>
      <RenderDesc />
      <ChartWrapper>
        <span className={styles.chart_title}>
          {"组合调仓"} ({chartTitle?.startDate} - {chartTitle?.endDate})
        </span>
        <Spin spinning={loadingEvent}>
          <div style={{ height: 186 }}>
            <EventLine
              idName="position-trend-chart"
              xAxis={xAxis}
              legend={legend}
              data={yAxis}
              color={["#3457C4", "#E85C36"]}
              pointLegend={portfolioName}
              isHoverPoint={false}
              isClickPoint={true}
              onClickPoint={onClickPoint}
              percent={true}
            />
          </div>
        </Spin>
      </ChartWrapper>
      <Wrapper>
        <div style={{ width: "69%", borderRight: "1px solid #E4E4E4" }}>
          {historyList ? (
            <FlexStart>
              <DateList height={515}>
                {historyList.map((item, index) => (
                  <DateLine
                    active={activeDateIndex == index}
                    activeColor={"#E64A00"}
                    onClick={() => changeDate(index)}
                  >
                    {item.buyDate}
                  </DateLine>
                ))}
              </DateList>
              <TableWrapper height={515}>
                <DisplayTable>
                  <Tr>
                    <Th pl={12}>基金代码</Th>
                    <Th pr={30}>产品名称</Th>
                    <Th pr={30}>基金类型</Th>
                    <Th align="right" pr={30}>
                      调仓前比例
                    </Th>
                    <Th align="right" pr={30}>
                      调仓后比例
                    </Th>
                    {/* <Th align="right" pr={30}>
                      收益贡献（调仓以来）
                    </Th>
                    <Th align="right" pr={30}>
                      风险贡献（调仓以来）
                    </Th> */}
                    <Th pr={30}>与上次变化</Th>
                    <Th pr={12}>备注</Th>
                  </Tr>
                  {historyList[activeDateIndex]?.list?.map((product, i) => (
                    <Tr>
                      <Td pl={12} minWidth={100}>
                        {product.secuCode}
                      </Td>
                      <Td minWidth={150} display={"block"} pr={30}>
                        {product.secuAbbr}
                      </Td>
                      <Td maxWidth={100}>{product.fundTypeName}</Td>
                      <Td minWidth={100} align="right" pr={30}>{`${(
                        product.portionBeforeChange * 100
                      ).toFixed(2)}%`}</Td>
                      <Td align="right" pr={30} minWidth={100}>{`${(
                        product.portion * 100
                      ).toFixed(2)}%`}</Td>
                      {/* <Td align="right" pr={30} minWidth={200}>{(product.revenueContribution == null || product.revenueContribution == 'null') ? '-': `${
                        product.revenueContribution}%`}</Td>
                      <Td align="right" pr={30} minWidth={200}>{(product.riskContribution == null || product.riskContribution == 'null') ? '-': `${
                        product.riskContribution}%`}</Td> */}
                      <Td pr={30} minWidth={100}>
                        {product.explain}
                      </Td>
                      <Td pr={12} minWidth={40}>
                        {product.remark}
                      </Td>
                    </Tr>
                  ))}
                </DisplayTable>
              </TableWrapper>
            </FlexStart>
          ) : (
            <PreviewEmpty />
          )}
        </div>
        <div style={{ width: "31%", padding: "4px 24px 27px 16px" }}>
          <ChartTitle>{`资产配置比例 (${historyList[activeDateIndex]?.buyDate})`}</ChartTitle>
          <div style={{ height: "45%" }}>
            <LittleTitle
              title="调仓前"
              mt="0"
              weight={400}
              family={"PingFangSC-Regular"}
            />
            {historyList[activeDateIndex]?.beforeChart ? (
              <Pie
                name=""
                idName="before-pie"
                pieData={historyList[activeDateIndex]?.beforeChart}
                {...pieOptions}
              />
            ) : (
              <EventEmpty
                title="暂无数据"
                style={{ paddingTop: 0 }}
              ></EventEmpty>
            )}
          </div>
          <div style={{ height: "45%" }}>
            <LittleTitle
              title="调仓后"
              mt="0"
              weight={400}
              family={"PingFangSC-Regular"}
            />
            {historyList[activeDateIndex]?.chart ? (
              <Pie
                name=""
                idName="after-pie"
                // legendData={creditList?.map((v) => v.firstIndustryName)}
                pieData={historyList[activeDateIndex]?.chart}
                {...pieOptions}
              />
            ) : (
              <EventEmpty
                title="暂无数据"
                style={{ paddingTop: 0 }}
              ></EventEmpty>
            )}
          </div>
        </div>
      </Wrapper>
    </PageWrapper>
  );
}

const Wrapper = styled.div`
  border: 1px solid #e4e4e4;
  min-width: 1068px;
  height: 531px;
  margin-top: 10px;
  display: flex;
`;

const ChartTitle = styled.div`
  font-weight: 600;
  font-size: 13px;
  color: #35425e;
  height: 28px;
  margin-top: 4px;
`;

const ChartWrapper = styled.div`
  height: 230px;
  background: #ffffff;
  border: 1px solid #e4e4e4;
  border-radius: 2px;
  position: relative;
  min-width: 532px;
  width: 100%;
  margin-top: 13px;
`;
